package userlimitModel

import (
	"arabApi/app/api/models"
	"arabApi/app/api/requests"
	"arabApi/app/api/requests/userlimitRequest"
	"arabApi/pkg/database"
	"arabApi/pkg/helpers"
	"github.com/spf13/cast"
)

type Users struct {
	models.BaseModel
	Name     string `gorm:"column:name" db:"name" form:"name" json:"name"`
	Email    string `gorm:"column:email" db:"email" form:"email" json:"email"`
	Phone    string `gorm:"column:phone" db:"phone" form:"phone" json:"phone"`
	Password string `gorm:"column:password" db:"password" form:"password"`
	State    int64  `gorm:"column:state" db:"State" form:"State" json:"state"`
	models.CommonTimestampsField
}

func (Users) TableName() string {
	return "users"
}

func UserList(r requests.PageStruct) ([]Users, int64) {
	var count int64
	dd := database.DB.Model(Users{})

	var users []Users
	p := cast.ToInt(r.Page)
	ps := cast.ToInt(r.PageSize)

	dd.Count(&count).Limit(ps).Offset((p - 1) * ps).Find(&users)
	return users, count
}

func (Users) UserAdd(r userlimitRequest.UserAdd) uint64 {
	u := &Users{}
	if err := helpers.Copy(r, u); err != nil {
		return 0
	}
	database.DB.Create(u)
	return u.ID

}

func GetMsgById(id int64) Users {
	var user Users
	database.DB.Model(Users{}).Where("id = ?", id).Find(&user)
	return user
}

func (Users) UserEdit(r userlimitRequest.UserAdd) error {
	u := &Users{}
	if err := helpers.Copy(r, u); err != nil {
		return err
	}
	res := database.DB.Where("id = ?", u.ID).Updates(u)
	return res.Error

}

//func Del(id int64) error {
//	var systemConfig1 int
//	ccc := database.DB.Where("id = ?", id).Update()
//	return ccc.Error
//}

func UserRoleMenu(userId int64) []map[string]interface{} {
	var result []map[string]interface{}

	database.DB.Table("tp_user_role").
		Select("tp_menu.*").
		Joins("inner join tp_role_menu on tp_user_role.role_id = tp_role_menu.role_id").
		Joins("inner join tp_menu on tp_role_menu.menu_id = tp_menu.id").
		Where("tp_user_role.user_id = ?", userId).Group("tp_role_menu.menu_id").Order("tp_menu.order").Find(&result)

	return result
}
